package cn.wolfcdoe.luowowo.comment.service.impl;

import cn.wolfcdoe.luowowo.comment.service.repository.StrategyCommentRepository;
import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {
    @Autowired
    private StrategyCommentRepository repository;//crud

    @Autowired
    private MongoTemplate template;//高级查询

    @Override
    public Page query(StrategyCommentQuery qo) {
        //查询评论列表  自己封装pange

        Query query = new Query();
        //查询条件
        if(qo.getDetailId()!=-1){
            query.addCriteria( Criteria.where("detailId").is(qo.getDetailId()));
        }

        Long count = template.count(query, StrategyComment.class);
        //如果没有值就直接返回空
        if(count==0){
           return  Page.empty();
        }
        //分页查询
        Pageable page = PageRequest.of(qo.getCurrentPage() - 1,qo.getPageSize(), Sort.Direction.DESC, "createTime");
        query.with(page);
        //查询所有
        List<StrategyComment> list = template.find(query, StrategyComment.class);

        return new PageImpl(list,page,count);
    }

    @Override
    public void commentThumbUp(String toid, Long uid) {
        //判断当前请求是点赞还是取消点赞
        StrategyComment comment = repository.findById(toid).get();
        if (comment==null){
            return;
        }
        //看一下list里面是否有用户id
        List<Long> thumbuplist = comment.getThumbuplist();
        if(!thumbuplist.contains(uid)){
            //如果不包含表示点赞,点赞数加一
            comment.setThumbupnum(comment.getThumbupnum() + 1);
            thumbuplist.add(uid);
        }else{
            comment.setThumbupnum(comment.getThumbupnum() - 1);
            thumbuplist.remove(uid);
        }
        //更新这条数据
        repository.save(comment);
    }

    @Override
    public void save(StrategyComment comment) {
        repository.insert(comment);
    }



}
